import { deviceType } from "@utils";
import bridgeMap from "./defineBridge";
import store from "../../store";
import router from "../../router";
import qs from "qs";
import cookie from "js-cookie";
/**
 * 与app通信，调用app方法
 * @param {*} action
 * @param {*传入时需要传对象格式} params
 */
export const appBridge = (action, params = {}) => {
  const device = deviceType();
  const bridge = {
    ...bridgeMap[action],
    content: Object.assign(bridgeMap[action].content, params)
  };
  if (device === "android") {
    App.onAppResponse(JSON.stringify(bridge));
  } else if (device === "ios") {
    window.webkit.messageHandlers.onAppResponse.postMessage(
      JSON.stringify(bridge)
    );
  }
};
/**
 * app返回的数据
 * @param {*app回传数据} res
 * @param {*额外的参数，某些action会用到} params
 * @returns 
 */
export const appResponse = (res, params = {}) => {
  const { action, content } = JSON.parse(res);
  switch (action) {
    case "setUserInfo":
      store.commit("getToken", content.token);
      store.commit("getSalt", content.salt);
      store.commit("LOGIN", content.ds_token);
      break;
    case "payResult":
      {
        const query = qs.stringify(Object.assign({ from1: "app" }, params));
        router.replace(`/order/status/${content.data.order_id}/2?${query}`);
      }
      break;
    case "onUploadImageSuccess":
      break;
    case "onAppClickBack":
      break;
    case "shareH5":
      break;
    default:
      break;
  }
  return Promise.resolve({ action, content });
};
